package com.example.mvcdemo.controller;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.example.mvcdemo.R;
import com.example.mvcdemo.model.ImageModel;

public class MainActivity extends AppCompatActivity implements Callback {

    private ImageView imgIv;
    private Button downloadBtn;
    private static final String IMAGE_URL = "http://imglf6.nosdn0.126.net/img/T2xtRUpvNXdwUVJWQm1QR2s2eklMNTZiOWxuYmxabmI3V1JaYW9KbHJNZ1VvZVVsMWp3WnB3PT0.jpg?imageView&thumbnail=266y200&type=jpg&quality=96&stripmeta=0&type=jpg";
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findView();
        initData();
    }

    private void initData() {
        handler = new Handler(new Handler.Callback() {

            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case ImageDownloader.SUCCESS:
                        imgIv.setImageBitmap((Bitmap) message.obj);
                        break;
                    case ImageDownloader.ERROR:
                        break;
                }
                return false;
            }
        });
        downloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageModel imageModel = new ImageModel();
                imageModel.setUrl(IMAGE_URL);
                ImageDownloader.download(MainActivity.this, imageModel);
            }
        });
    }

    private void findView() {
        imgIv = findViewById(R.id.activity_main_image_iv);
        downloadBtn = findViewById(R.id.activity_main_download_img_btn);
    }

    @Override
    public void callback(int resultCode, ImageModel bitmap) {
        Message message = handler.obtainMessage(resultCode);
        message.obj = bitmap.getBitmap();
        handler.sendMessage(message);
    }
}
